<template>
	<el-tree :data="treeData" :props="defaultProps" :load="loadNode" lazy ref="dbTree">
		<span class="custom-tree-node" slot-scope="{ node, data }">
			<i :class="data.icon"></i>
			{{ node.label }}
		</span>
	</el-tree>
</template>

<script>
export default {
	data(){
		return {
			node: [],
			resolve: [],
			treeData: [],
			defaultProps: {
				children: 'children',
				label: 'text'
			}
		}
	},
	computed: {
		getDb(){
			return this.$store.state.dbInstance;
		}
	},
	watch:{
		getDb(){
			this.getSchemas();
		}
	},
	methods: {
		async getSchemas() {
			const params = {
				resourceId: this.$store.state.dbInstance
			};
			const result = await this.$http.get('/db/schemas', {params: params});
			this.treeData = result.data;
		},
		async getTableStruct(dbName) {
			const params = {
				resourceId: this.$store.state.dbInstance
			};
			const {data} = await this.$http.get(`/db/tables/${dbName}`, {params:params});
			this.$store.commit('loadTableStruct', data);
		},
		filterNode: function(value, data){
			if (!value) return true;
			return data.label.indexOf(value) !== -1;
		},
		loadNode(node, resolve) {
			let store = this.$store;
			if(node.level === 0) {
				this.node = node;
				this.resolve = resolve;
				return resolve([]);
			}else if(node.level === 1){
				store.commit('setDatabase', node.data.text);
				return resolve(node.data.children);
			}else{
				if(node.data.text !== '表') return resolve([]);
				const params = {
					resourceId: this.$store.state.dbInstance
				};
				store.commit('setDatabase', node.data.db);
				this.$http.get(`/db/instance/${node.data.db}`,{params:params}).then(response => {
					return resolve(response.data);
				});
				this.$store.commit('changeTab', 'obj');
				this.getTableStruct(node.data.db);
			}
		}
	}
}
</script>
